package org.ithasu.tools;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class IOTools {

	protected static int IO_BUFFER_SIZE = 4096;

	private IOTools() {
	}

	// -- Bytes manipulation ----------------------------------------

	public static byte toByte(int i) {
		int unsignedByte = i & (0xff);
		return (byte) unsignedByte;
	}

	public static String toHexByte(int b) {
		return "0x" + Integer.toHexString(b & 0xff);
	}

	public static int readInt(byte l, byte h) {
		int res = h & 0xff;
		res = res << 8;
		res = res | (l & 0xff);
		return res;
	}

	// -- File ----------------------------------------

	public static byte[] read(InputStream stream) {
		try {
			stream.reset();
		} catch (IOException e1) {
			// Don't care about exception
			// Console.error(e1);
		}

		try {
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[IO_BUFFER_SIZE];
			int size = 0;
			do {
				size = stream.read(buffer);
				if (size > 0) {
					output.write(buffer, 0, size);
				}
			} while (size >= 0);

			return output.toByteArray();
		} catch (Exception e) {
			Console.error(e);
			return null;
		}
	}

	// -- Serial ----------------------------------------

	public static SerialPort serial_connect(String device, int baudrate) {
		try {
			CommPortIdentifier portIdentifier = CommPortIdentifier
					.getPortIdentifier(device);

			CommPort commPort;
			commPort = portIdentifier.open("", 2000);
			if (commPort instanceof SerialPort) {
				SerialPort serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(baudrate, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
				return serialPort;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// -- Folders ------------------------------------------------

	public static String getTmpFolder() {
		return System.getProperty("java.io.tmpdir");
	}
}
